package com.sa.stp.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.bluetooth.BluetoothClass.Device;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sa.stp.R;
import com.sa.stp.parser.ItemParser;
import com.sa.stp.parser.ItemParserImpl;
import com.sa.stp.services.Service;
import com.sa.stp.utilities.ImageDownloader;
import com.sa.stp.utilities.NFCHandler;
import com.sa.stp.utilities.Utilities;

public class ItemActivity extends Activity implements OnClickListener {

	private static final float MIN_GPS_ACCURACY = 80f;

	private ItemParser parser;

	// Temporales
	private String textoGPS = "Sin coordenadas aun";
	private TextView etiquetaGPS;

	// GPS
	private static LocationManager locationManager;
	private static LocationListener locationListener;
	private static Location currentBestLocation;

	// etiquetaGPS.setText(textoGPS);

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item);

		Intent intent = getIntent();

		TextView manufacturer = (TextView) findViewById(R.id.lb_manufacturer);
		// Temporales

		etiquetaGPS = (TextView) findViewById(R.id.lb_manufacturer);
		Button botonAux = (Button) findViewById(R.id.button_aux);
		botonAux.setOnClickListener(this);

		// GPS
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationListener = new MyLocationListener();
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, locationListener);

		// Vengo de ItemsActivity
		if (intent.getAction().equals("ItemsActivity")) {

			parser = new ItemParserImpl(getIntent().getStringArrayExtra("item"));

			// Vengo por NFC
		} else {

			String contenido = NFCHandler.resolveIntent(getIntent(), this);
			// parser

			String[] itemArray = contenido.split(";");
			String vendor = itemArray[2];
			String model = itemArray[3];

			// Si es la primaera vez que lo tagueamos, descargamos su XML
			if (!Utilities.modelAlreadyTagged(vendor, model)) {
				String urlBase = itemArray[1];
				if (ImageDownloader.downloadAndStoreXml(urlBase, vendor, model)) {
					Toast.makeText(ItemActivity.this,
							vendor + " " + model + "Downloaded successfully",
							Toast.LENGTH_SHORT).show();
				}
			}
			//TODO: Preguntar al usuario el alias del item
			parser = new ItemParserImpl(vendor, model, "");

		}

		// Servicios
		ExpandableListView services = (ExpandableListView) findViewById(R.id.expandableListViewServices);
		services.setAdapter(new ExpandableServicesListAdapter(this));
		
		
		manufacturer.setText(parser.getValueFromXML("manufacturer") + " " + parser.getValueFromXML("model"));

	}

	@Override
	public void onNewIntent(Intent intent) {
		setIntent(intent);
		NFCHandler.resolveIntent(intent, this);
	}

	public class ExpandableServicesListAdapter extends
			BaseExpandableListAdapter {

		@Override
		public boolean areAllItemsEnabled() {
			return true;
		}

		private Context context;

		private ArrayList<String> groups;

		private ArrayList<ArrayList<Service>> children;

		public ExpandableServicesListAdapter(Context context) {
			
			this.context = context;
			this.groups = new ArrayList<String>();
			this.children = new ArrayList<ArrayList<Service>>();

			groups.add("Virtual Services");
			groups.add("Actions");
			
			children.add(new ArrayList<Service>());
			children.add(new ArrayList<Service>());

			children.get(0).addAll(parser.getVirtualServices());
			children.get(1).addAll(parser.getRealServices());

		}

		public ExpandableServicesListAdapter(Context context,
				ArrayList<String> groups, ArrayList<ArrayList<Service>> children) {
			this.context = context;
			this.groups = groups;
			this.children = children;
		}

		public Object getChild(int groupPosition, int childPosition) {
			return children.get(groupPosition).get(childPosition);
		}

		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		// Return a child view. You can load your custom layout here.

		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			Service service = (Service) getChild(groupPosition, childPosition);
			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater
						.inflate(R.layout.child_layout, null);
			}
			TextView tv = (TextView) convertView.findViewById(R.id.tvChild);
			tv.setText("   " + service.getName());

			// Depending upon the child type, set the imageTextView01
			tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			if (service instanceof Device) {
				tv.setCompoundDrawablesWithIntrinsicBounds(
						R.drawable.android_icon, 0, 0, 0);
			}
			return convertView;
		}

		public int getChildrenCount(int groupPosition) {
			return children.get(groupPosition).size();
		}

		public Object getGroup(int groupPosition) {
			return groups.get(groupPosition);
		}

		public int getGroupCount() {
			return groups.size();
		}

		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		// Return a group view. You can load your custom layout here.

		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			String group = (String) getGroup(groupPosition);
			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater
						.inflate(R.layout.group_layout, null);
			}
			TextView tv = (TextView) convertView.findViewById(R.id.tvGroup);
			tv.setText(group);
			return convertView;
		}

		public boolean hasStableIds() {
			return true;
		}

		public boolean isChildSelectable(int arg0, int arg1) {
			return true;
		}

	}

	// Objeto LocationListener propio
	private class MyLocationListener implements LocationListener {

		public void onLocationChanged(Location location) {

			Double lat = location.getLatitude();
			Double log = location.getLongitude();
			textoGPS = lat + " : " + log;
			if (currentBestLocation != null
					&& currentBestLocation.getAccuracy() >= location
							.getAccuracy()) {

			} else if (currentBestLocation == null) {
				currentBestLocation = location;
			}

			if (location.getAccuracy() < MIN_GPS_ACCURACY) {
				locationManager.removeUpdates(locationListener);

			}

		}

		public void onProviderDisabled(String provider) {

		}

		public void onProviderEnabled(String provider) {

		}

		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.button_aux) {
			etiquetaGPS.setText(textoGPS);
		}
	}
}
